package system

import (
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	"go-admin/common/config"
	"go-admin/pkg/logger"
	"log"
	"net/http"
)

/**
* @Description:
* @Author: yuweizhu
* @Date: 2020/11/15 11:00 下午
**/
func Redirect(c *gin.Context) {
	if c.Request.RequestURI == "/favicon.ico" {
		c.String(http.StatusNotFound, "")
		return
	}

	res, err := config.GetRedis().HGetAll(c, c.Request.RequestURI).Result()
	if err != nil {
		log.Printf("查找短链接失败，error: %v\n", err)
		//cc := config.GetConfig().GetStringStringMapValue("shortLinkNotFoundConfig",
		//	config.GetDefaultShortLinkNotFoundConfig())
		//
		//switch cc["mode"] {
		//case config.ShortLinkNotFoundContentMode:
		//	c.String(http.StatusOK, cc["value"])
		//	break
		//case config.ShortLinkNotFoundRedirectMode:
		//	c.Redirect(http.StatusTemporaryRedirect, cc["value"])
		//	break
		//default:
		//	c.String(http.StatusOK, "你访问的页面不存在哦")
		//}

		return
	}

	//if res["status"] != "1" {
	//	// TODO 余额不足 充钱
	//	//	c.String(http.StatusOK, "你访问的页面不存在哦")
	//	return
	//}

	// TODO 异步扣除访问点数
	var urlData models.TShortUrl
	urlData.Status = "1"
	urlData.Uri = c.Request.RequestURI
	urlData.ClickAmount = 1
	err = urlData.DecreaseClick()
	if err != nil {
		logger.Logger.Infof("err :%+v\n", err)
		c.String(http.StatusOK, "你访问的页面不存在哦")
	}

	// 保存短链接请求记录（IP、User-Agent），保存活跃链接记录
	//rhRepo := repository.GetRequestHistoryRepo(db.GetRedisClient())
	//alRepo := repository.GetActiveLinkRepo(db.GetRedisClient())
	//go func() {
	//	rhRepo.Save(models.NewRequestHistory(s, c.ClientIP(), c.Request.UserAgent()))
	//	alRepo.Save(s.Id)
	//}()

	c.Redirect(http.StatusTemporaryRedirect, res["url"])
}
